﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    // 实例
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            // 规则相关权限
            rulePermission: true, // 等进到本页面就是 true
            ruleAddPermission: false,
            ruleEditPermission: false,
            ruleDeletePermission: false,
            // 规则组权限
            ruleGroupPermission: false,
            ruleGroupAddPermission: false,
            ruleGroupEditPermission: false,
            ruleGroupDeletePermission: false,

            multiDepartmentPermission: false,

            tableData: [],

            level: null,
            hospital: null,
            department: null,   // 当前科室
            deviceType: null,    // 当前设备类型
            device: null,
            treeData: [],

            groupLabelWidth: '80px',
            ruleGroupOptions: [], // 规则组选项
            logicTypeOptions: [], // 逻辑类型选项
            levelOptions: [],      // 层级选项 

            ruleGroup: { // 规则组
                id: null,
                level: null,
                name: null,
                order: 0,
                isActive: true,
                description: null,
                departmentId: null,
                deviceTypeId: null,
                deviceId: null,
            },
            groupActionType: 'add',
            ruleGroupDialogTitle: '新建规则组',
            ruleGrupDialogVisible: false,

            rule: { // 规则
                id: null,
                level: null,
                name: null,
                script: null,
                logicType: 0,
                ruleGroupId: null,
                description: null,
                order: 0,
                isActive: true,
                departmentId: null,
                deviceTypeId: null,
                deviceId: null
            },
            ruleLabelWidth: '70px',
            ruleActionType: 'add',
            ruleDialogTitle: '新建规则',
            ruleDialogVisible: false,
            language: 'text/x-csharp',

            selectedGroup: null,

            defaultProps: {                 // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则（规则表单）
            validateRules: {

            },

            // 验证规则 (规则组表单)
            validateGroupRules: {

            }
        },
        components: {
            'code-mirror': CodeComponent
        },
        computed: {
            levelPathName() {
                const vm = this;
                var pathName;
                switch (vm.level) {
                    case 0: // 全局
                        pathName = vm.hospital;
                        break;

                    case 1:// 科室级
                        pathName = `${vm.hospital}--${vm.department.name}`;
                        break

                    case 2:// 科室设备类型级别
                        pathName = `${vm.hospital}--${vm.department.name}--${vm.deviceType.name}`;
                        break;

                    case 3:// 设备级
                        pathName = `${vm.hospital}--${vm.department.name}--${vm.deviceType.name}--${vm.device.name}`;
                        break;
                }
                return pathName;
            }
        },
        watch: {

        },
        methods: {

            // 加载表格数据
            loadTableData() {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/rule/get-table-data?level=${vm.level}&depId=${vm.department ? vm.department.id :''}&deviceTypeId=${vm.deviceType ? vm.deviceType.id : ''}&deviceId=${vm.device ? vm.device.id : ''}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data;
                        vm.ruleGroupOptions = res.data.map(item => { return { label: item.name, value: item.id } });
                    }
                })
            },

            // 加载某个规则组下的规则列表
            loadRuleTableData(groupId) {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/rule/get-group-rules?groupId=${groupId}`
                }).then(res => {
                    if (res.code === 0) {
                        var index = vm.tableData.findIndex(item => item.id === groupId);
                        vm.tableData[index].rules = res.data;
                    }
                })
            },

            // 自定义表单验证器
                // 必填，不为空
            isRequired(rule, value, callback) {
                const vm = this;
                if (value === null || value === '') {
                    return callback(new Error('必填'));
                }
                callback();
            },

                // 必须为整型
            isInteger(rule, value, callback) {
                if (value!==0 && !value) {
                    return callback(new Error('不能为空'));
                }
                if (!Number.isInteger(Number(value))) {
                    return callback(new Error('必须为整数'));
                }
                callback();
            },

            // 获取规则组详情
            getGroupDetail(id) {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/rule/get-rule-group-detail?id=${id}`,
                }).then((res) => {
                    if (res.code === 0) {
                        vm.ruleGroup = res.data;
                    }
                })
            },

            // 获取规则详情
            getRuleDetail(id) {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/rule/get-rule-detail?id=${id}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.rule = res.data;
                    }
                })
            },

            // 新建规则
            showRuleCreate() {
                const vm = this;
                if (!vm.selectedGroup) {
                    abp.notify.error('请先选中规则组')
                } else {
                    vm.ruleActionType = 'Add';
                    vm.rule.logicType = 0; // 默认逻辑与
                    vm.rule.ruleGroupId = vm.selectedGroup.id;
                    vm.rule.level = vm.level;
                    vm.ruleGroupId = vm.selectedGroup.id;
                    vm.rule.order = 0;
                    vm.rule.isActive = true;
                    vm.rule.departmentId = vm.department ? vm.department.id : null;
                    vm.rule.deviceTypeId = vm.deviceType ? vm.deviceType.id : null;
                    vm.rule.deviceId = vm.device ? vm.device.id : null;
                    vm.rule.script = '';
                    vm.ruleDialogVisible = true;
                }
                
            },

            // 编辑规则
            showRuleEdit(id) {
                const vm = this;
                vm.ruleActionType = 'Edit';
                abp.ajax({
                    type: 'get',
                    url:`/api/rule/get-rule-detail?id=${id}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.rule = res.data;
                        vm.ruleDialogVisible = true;
                    }
                })
            },

            // 删除规则
            deleteRule(row) {
                const vm = this;
                debugger;
                abp.message.confirm('删除规则')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/rule/delete-rule?id=${row.id}`,
                            }).then(res => {
                                if (res.code == 0) {
                                    abp.notify.success(res.msg);
                                    debugger;
                                    vm.loadRuleTableData(row.ruleGroupId);
                                }
                            })
                        }
                    })
            },

            // 保存规则 
            saveRule() {
                const vm = this;
                var url;
                if (vm.ruleActionType === 'Add') {
                    url = `/api/rule/rule-create-submit`;
                } else {
                    url = `/api/rule/rule-edit-submit`;
                }
                vm.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: url,
                            data: JSON.stringify(vm.rule)
                        }).then(res => {
                            if (res.code === 0) {
                                vm.loadRuleTableData(vm.rule.ruleGroupId);
                                abp.notify.success(res.msg);
                            }
                        });
                    }
                })
            },

            // 新建规则组
            showRuleGroupCreate() {
                const vm = this;
                vm.ruleGroup.order = 0;
                vm.ruleGroup.isActive = true;
                vm.ruleGroup.departmentId = vm.department ? vm.department.id : null;
                vm.ruleGroup.deviceTypeId = vm.deviceType ? vm.deviceType.id : null;
                vm.ruleGroup.deviceId = vm.device ? vm.device.id : null;
                vm.ruleGroup.level = vm.level;
                vm.ruleGroupDialogTitle = '新建规则组';
                vm.groupActionType = 'Add';
                vm.ruleGrupDialogVisible = true;
            },

            // 编辑规则组
            showRuleGroupEdit(id) {
                const vm = this;
                vm.groupActionType = 'Edit';
                vm.getGroupDetail(id);
                vm.ruleGrupDialogVisible = true;
            },

            // 删除规则组
            deleteRuleGroup(id) {
                const vm = this;
                abp.message.confirm('删除规则组，则规则组下所有规则将被删除.')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/rule/delete-rule-goup?id=${id}`,
                            }).then(res => {
                                if (res.code == 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadTableData();
                                }
                            })
                        }
                    })
            },

            // 保存规则组
            saveRuleGroup() {
                const vm = this;
                var url;
                if (vm.groupActionType === 'Add') {
                    url = `/api/rule/rule-group-create-submit`;
                } else {
                    url = `/api/rule/rule-group-edit-submit`;
                }
                abp.ajax({
                    type: 'post',
                    url: url,
                    data: JSON.stringify(vm.ruleGroup)
                }).then(res => {
                    if (res.code === 0) {
                        abp.notify.success(res.msg);
                        vm.loadTableData();
                        vm.ruleGrupDialogVisible = false;
                        vm.resetRuleGoupForm();
                    }
                })
            },

            // 加载科室（如果是科室用户时）
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 到诊模式选项加载
            loadRuleGroupOptions() {
                const vm = this;
                abp.ajax({
                    type: "GET",
                    url: `/api/rule/get-group-options?level=${vm.level}&`
                }).then(res => {
                    if (res.code === 0) {
                        vm.ruleGroupOptions = res.data;
                    }
                })
            },

            // 加载逻辑类型选项
            loadLogicTypeOptions() {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: '/api/rule/get-logic-type-options'
                }).then(res => {
                    if (res.code === 0) {
                        vm.logicTypeOptions = res.data;
                    }
                })
            },

            // 加载层级选项
            loadLevelOptions() {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: '/api/rule/get-level-options'
                }).then(res => {
                    if (res.code === 0) {
                        vm.levelOptions = res.data;
                    }
                })
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                const vm = this;
                return new Promise(resolve => {
                    var url;
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        url = `/api/custom-setting/get-tree-data?depId=`
                    }
                    else {
                        url = `/api/custom-setting/get-tree-data?depId=${vm.department.id}`
                    }
                    abp.ajax({
                        type: "GET",
                        url: url
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            vm.level = 0;
                            vm.hospital = res.data[0].name;
                            resolve();
                        }
                    });
                });
            },



            // 规则表单重置
            resetRuleForm() {
                const vm = this;
                vm.$refs['ruleForm'].resetFields();
                Object.keys(vm.rule).forEach(key => {
                    if (key === 'script') {
                        vm.rule[key] = '';
                    } else {
                        vm.rule[key] = null;
                    }
                });
            },

            // 规则组表单重置
            resetRuleGoupForm() {
                const vm = this;
                vm.$refs['ruleGroupForm'].resetFields();
                Object.keys(vm.ruleGroup).forEach(key => {
                    vm.ruleGroup[key] = null;
                })
            },

            selectedGroupChange(val) {
                const vm = this;
                vm.selectedGroup = val;
            },

            // 加载当前权限
            loadPermission() {
                const vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('RuleGroup.Rules') && abp.auth.isGranted('RuleGroup.RuleGroups')) { // 根权限
                        vm.rulePermission = true;
                        vm.ruleGroupPermission = true;
                        if (abp.auth.isGranted('RuleGroup.RuleGroups.Add')) { // 新建规则组权限
                            vm.ruleAddPermission = true;
                        }
                        if (abp.auth.isGranted('RuleGroup.RuleGroups.Delete')) { // 删除规则组权限
                            vm.ruleDeletePermission = true;
                        }
                        if (abp.auth.isGranted('RuleGroup.RuleGroups.Edit')) { // 编辑规则组权限
                            vm.ruleEditPermission = true;
                        }
                        if (abp.auth.isGranted('RuleGroup.Rules.Add')) { // 新建规则权限
                            vm.ruleGroupAddPermission = true;
                        }
                        if (abp.auth.isGranted('RuleGroup.Rules.Edit')) { // 编辑规则权限
                            vm.ruleGroupEditPermission = true;
                        }
                        if (abp.auth.isGranted('RuleGroup.Rules.Delete')) { // 删除规则权限
                            vm.ruleGroupDeletePermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) { // 多科室检查项目管理权限
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击树节点
            nodeClicked(node, obj, aa) {
                const vm = this;
                switch (node.level) {
                    case 'hospital':
                        vm.level = 0;
                        vm.hospital = node.name;
                        vm.department = null;
                        vm.deviceType = null;
                        vm.device = null;
                        break;

                    case 'department':
                        vm.level = 1;
                        vm.department = {
                            id: node.id,
                            name: node.name
                        }
                        vm.deviceType = null;
                        vm.device = null;
                        break;

                    case 'deviceType':
                        vm.level = 2;
                        var depNode = obj.parent.data
                        vm.department = {
                            id: depNode.id,
                            name: depNode.name
                        };
                        vm.deviceType = {
                            id: node.id,
                            name: node.name
                        };
                        vm.device = null;
                        break;

                    case 'device':
                        vm.level = 3;
                        var depNode = obj.parent.parent.data;
                        vm.department = {
                            id: depNode.id,
                            name: depNode.name
                        }
                        var deviceTypeNode = obj.parent.data;
                        vm.deviceType = {
                            id: deviceTypeNode.id,
                            name: deviceTypeNode.name
                        }
                        vm.device = {
                            id: node.id,
                            name: node.name
                        }
                }
                vm.selectedGroup = null;
                vm.loadTableData();
            },

            // 初始化
            init() {
                const vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                vm.loadTableData();
                            });
                        });
                        vm.loadLevelOptions();     // 加载层级选项
                        vm.loadLogicTypeOptions(); // 加载逻辑类型 
                    });
            }
        },
        created() {
            const vm = this;
            // 创建验证规则
            vm.validateRules = {
                name: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                typeName: [
                    {
                        validator: vm.isRequired,
                        trigger: ['blur']
                    }
                ],
                order: [
                    {
                        validator: vm.isInteger,
                        trigger: ['blur']
                    }
                ]
            };
            vm.validateGroupRules = {
                name: [
                    {
                        validator: vm.isRequired,
                        trigger:['blur']
                    }
                ]
            }
        },
        mounted() {
            const vm = this;
            vm.init();
        }
    });
});